'use strict';
var gulp = require('gulp'),
    runSequence = require('run-sequence'),
    postcss = require('gulp-postcss'),
    autoprefixer = require('autoprefixer'),
    plugins = require('gulp-load-plugins')();

//watchfy擴展
var watchify = require('watchify');
var browserify = require('browserify');
var buffer = require('vinyl-buffer');
var source = require('vinyl-source-stream');
var sourcemaps = require('gulp-sourcemaps');
var assign = require('lodash.assign');
var gutil = require('gulp-util');
var livereload = require('browserify-livereload');
var path = require('path');
// watchify.args,
var opts = assign({}, {
    entries: './js/rc.js',
    debug: true,
    cache: {},
    packageCache: {}
});
var options = {
    port: 1212,
    start: true
};
var b = browserify(opts);

b.plugin(livereload, {
    host: 'localhost',
    port: 1337,
    outfile: path.join(__dirname, 'js', 'bundle.js') /* this option is required if using API mode */
});

var watchB = watchify(b);

var bundler = function() {
    return watchB.bundle()
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('js'))
        .pipe(plugins.livereload());
};

var build = function() {
    return b.bundle()
        .pipe(source('bundle.js'))
        .pipe(buffer())
        .pipe(plugins.rename({ suffix: '.min' }))
        .pipe(plugins.uglify())
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(gulp.dest('js'))
        .pipe(plugins.livereload());
};

b.on('update', bundler); // on any dep update, runs the bundler
gulp.task('js:watchfy', bundler);
gulp.task('js:bundle', build);
// //less编译合并
/*
sourceMap: {
        sourceMapURL: sourceMapFileName,
        sourceMapBasepath: lessFile.base,
        sourceMapRootpath: '../less', // Optional absolute or relative path to your LESS files
        sourceMapFileInline: false
    }
*/
gulp.task('less', function() {
    var processors = [
        autoprefixer({
            browsers: ['last 3 version'],
            cascade: false,
            remove: false
        })
    ];
    return gulp.src(['less/rc.less'])
        .pipe(plugins.concat('rc.less'))
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.less({
            sourceMap: {
                sourceMapRootpath: '../less'
            }
        }))
        .pipe(postcss(processors))
        .pipe(plugins.cssbeautify())
        .pipe(sourcemaps.write(''))
        .pipe(gulp.dest('css/'))
        .pipe(plugins.rename({ suffix: '.min' }))
        .pipe(plugins.minifyCss({ compatibility: 'ie6' }))
        .pipe(gulp.dest('css/'))
        .pipe(plugins.livereload());
});

//js合并压缩
gulp.task('js:vendor', function() {
    gulp.src(
            [
                // 'lib/jquery.tools.min.js',
                'lib/jquery.1.7.1.js',
                'lib/jquery.custom-scrollbar2.js',
                // 'lib/jquery.unslider.js',
                'lib/base64.js',
                'lib/underscore.js',
                'lib/backbone.js',
                'lib/swfobject.js'
            ])
        .pipe(plugins.concat('vendor.js'))
        .pipe(plugins.rename({ suffix: '.min' }))
        .pipe(plugins.uglify())
        .pipe(gulp.dest('js/dist'))
        .pipe(plugins.livereload());
});

//images复制
gulp.task('images', function() {
    gulp.src('pic/**')
        .pipe(plugins.imagemin())
        .pipe(gulp.dest('img'));
});

//開發监听
gulp.task('watch', function() {
    plugins.livereload.listen(options);
    gulp.watch('less/**/*.less', ['less']);
    gulp.watch('lib/*.js', ['js:vendor']);
    gulp.watch('pic/**/*.(png|jpg|gif)', ['images']);
});

//执行壓縮靜態類資源非邏輯代碼js
gulp.task('dev', function() {
    runSequence(
        ['less'], ['watch'], ['js:watchfy']
    )
});

gulp.task('build', function() {
    runSequence(
        ['less'], ['js:vendor'], ['images'], ['js:bundle']
    )
});

gulp.task('default', function() {
    runSequence(
        ['build'], ['dev']
    )
});